package edu.bw.dao.Impl;

import edu.bw.dao.ProductDao;
import edu.bw.po.Product;
import edu.bw.utils.ConnectionFactory;
import lombok.Setter;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

@Setter
@Repository
public class ProductDaoImpl implements ProductDao {

    @Autowired
    private QueryRunner queryRunner;

    @Autowired
    private ConnectionFactory connectionFactory;

    @Override
    public void saveProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConnection(),
                    "INSERT INTO spring.product(pname,price,category) VALUES (?,?,?)"
            ,product.getPname(),product.getPrice(),product.getCategory());

        }catch (SQLException e){
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateProduct(Product product) {
        try {
            queryRunner.update(connectionFactory.currentThreadConnection(),"UPDATE spring.product SET pname=?,price=?,category=? WHERE pid=?",
                    product.getPname(),product.getPrice(),product.getCategory(),product.getPid());
//            int i=1/0;
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }



    }

    @Override
    public void deleteProduct(Integer pid) {
        try {
            queryRunner.update(connectionFactory.currentThreadConnection(),
                    "DELETE FROM spring.product WHERE pid=?", pid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Product> findAll() {
        try {
            return queryRunner.query("SELECT * FROM spring.product",
                    new BeanListHandler<Product>(Product.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }



}
